extends Node

class_name Items

enum ItemTypes {
	item,
	food,
	weapon,
}
var itemTypes = [
	'Item',
	'Food',
	'Weapon'
]

var foodTypes = []
var itemProtoTypes = []
var items = []

func _ready():
	loadItemsTypes()
	createItems('res://物品/植物/barrerBush.tscn', 1, Vector2i(2, 2))
	createItems('res://物品/植物/barrerBush.tscn', 1, Vector2i(4, 2))
	# getFoodType()
	# addFood(foodTypes[0], Vector2( - 3, 1))

# 获取所有种类食物场景
func getFoodType():
	var path = "res://物品/食物/"
	var dir = DirAccess.open(path)
	dir.list_dir_begin()
	while true:
		var fileName = dir.get_next()
		if !fileName: break

		if fileName.ends_with(".tscn"): foodTypes.append(load(path + fileName))
	dir.list_dir_end()
# 向地图中添加食物
func addFood(itemScene: PackedScene, pos: Vector2) -> void:
	var item = itemScene.instantiate()
	item.position = MapToWorldPos(pos)
	add_child(item)
	items.append(item)

# 加载物品类
func loadItemsTypes():
	var itemsPath = Items._dir_contents('res://物品/', '.tscn')
	for path in itemsPath:
		itemProtoTypes.append(load(path))
		print(path)

#生成物品各从其类
func createItems(itemName: String, amount: int, mapPos: Vector2i):
	var newItem
	for proto in itemProtoTypes:
		if proto.get_path() != itemName: continue
		newItem = proto.instantiate()
		newItem.count = amount
	if newItem:
		items.append(newItem)
		add_child(newItem)
		newItem.position = MapToWorldPos(mapPos)

# 地图坐标转为世界坐标
func MapToWorldPos(pos: Vector2i) -> Vector2:
	return Vector2(pos.x * 16, pos.y * 16)

# 世界坐标转为地图坐标
func WorldToMapPos(pos: Vector2) -> Vector2i:
	return Vector2(pos.x / 16, pos.y / 16)

func isItemType(item: Item, typeIndex: ItemTypes) -> bool:
	return item.is_in_group(itemTypes[typeIndex])

# 搜索最近的某类物品
func findNearstItem(typeIndex: ItemTypes, position: Vector2) -> Item:
	if len(items) == 0: return
	var nearst = null
	var dis = 9999
	for item in items:
		if !isItemType(item, typeIndex): return null
		var curDis = position.distance_to(item.position)
		if nearst == null:
			nearst = item
			dis = curDis
			continue

		if curDis < dis:
			nearst = item
			dis = curDis
			
	return nearst

# 移除物品
func remove(item: Item):
	remove_child(item)
	items.erase(item)

# 获取目录下所有指定文件路径
static func _dir_contents(path, suffix) -> Array[String]:
	var dir = DirAccess.open(path)
	if !dir:
		print('错误加载的路径：%s' % [path])
		return []
		
	var files: Array[String] = []
	dir.list_dir_begin()
	var fileName = dir.get_next()
	while fileName != '':
		fileName = fileName.replace('.remap', '')
		if dir.current_is_dir():
			files.append_array(_dir_contents("%s/%s" % [path, fileName], suffix))
		elif fileName.ends_with(suffix):
			files.append('%s/%s' % [path, fileName])
		fileName = dir.get_next()

	return files